import { ref, watch } from 'vue'
import { usePreferredDark } from '@vueuse/core'

const isDark = ref(false)
const preferredDark = usePreferredDark()

export const useTheme = () => {
  const setTheme = (theme: 'auto' | 'dark' | 'light') => {
    if (theme === 'auto') {
      isDark.value = preferredDark.value
    } else {
      isDark.value = theme === 'dark'
    }

    if (isDark.value) {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }

  watch(preferredDark, () => {
    setTheme('auto')
  })

  return {
    isDark,
    setTheme,
  }
}
